package com.huaqin.customer;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

import com.huaqin.common.Featrue;
import com.huaqin.common.Util;
import com.huaqin.customer.expansion.MessageItem;
import com.huaqin.salestracker.SalesTrackerService;

/**
 *发送相关类：发送格式
 * @author nixionglin
 *
 */
public class MessageManager {
	private static final String TAG = "MessageManager";
	private String mAddressConfig = null;
	private String mMessageConfig = null;
	private String mMessage = null;
	private List<String> mItemList = null;
	private List<Address> mAddressList = null;
	private int mLastAddressIndex = -1; //The last use address index
	private Context mContext ;	
	
	//SIM Card send mode in SMS send
	private static final int SMS_SEND_MODE_SMS1 = 0; //Match Phone.java GEMINI_SIM_1 = 0
	private static final int SMS_SEND_MODE_SMS2 = 1; //Match Phone.java GEMINI_SIM_2 = 1
	private static final int SMS_SEND_MODE_SMS = 2; 
	private int mSMSSendMode = SMS_SEND_MODE_SMS1;

	private boolean mSendFail = false;

	public MessageManager(){
		mItemList = new ArrayList<String>();
	}
	
	public void setContext(Context context){
		mContext = context;
	}
	
	public void setMessageName(String MsgConfig){
		mMessageConfig = MsgConfig;
	}
	
	public void addMessageParam(String param){
		mItemList.add(param);
	}
	
	public void setMessageSendAddress(String address){
		mAddressConfig = address;
	}

    /**
     * 检查传入的地址有效性几个原则：
     */
	public static boolean isValidAddress(String address){

		return true;
    }
	
	public void Init(){

		if(Featrue.isDebug){
			Log.d(TAG,  "address parser start: [" + mAddressConfig + "]");
		}
		
		AddressParser addressParser = new AddressParser(mAddressConfig);

		try {
			addressParser.parserAddress();
			mAddressList = addressParser.getAddressList();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if(Featrue.isDebug){
			for(int i = 0; i < mAddressList.size(); i++){
				Address addr = mAddressList.get(i);
				Log.d(TAG, "orderAddress[" + i + "]: " + addr.getAddressIndex() + ": " + addr.getAddress());
			}

			Log.d(TAG,  "address parser end");
		}
		
//		mContext = 

	}

	public void setSMSSendMode(String mode){
		
		if(SalesTrackerService.MTK_GEMINI_SUPPORT){
			if("SIM".equalsIgnoreCase(mode)){
				mSMSSendMode = SMS_SEND_MODE_SMS;
			}
			else if("SIM1".equalsIgnoreCase(mode)){
				mSMSSendMode = SMS_SEND_MODE_SMS1;
			}
			else if("SIM2".equalsIgnoreCase(mode)){
				mSMSSendMode = SMS_SEND_MODE_SMS2;
			}
		}
		else{
			mSMSSendMode = SMS_SEND_MODE_SMS1;
		}
	}
	
	public int getSMSSendMode(){
		return mSMSSendMode;
	}

	/**
	 * 将配置的一个或多个地址解析成单个独立的地址
	 * 
	 * 地址解析规则：
	 * 地址内容组成：短信 -- 数字号码  Http -- www http com 等关键字符串  Email -- com
	 * 地址选择顺序：顺序从前往后选择 -- ＆分隔地址内容  随机地址内容 |
	 * 地址是否可复用：地址前无＊号表示可复用，地址添加＊号表示地址用过后不可复用
	 * 
	 * 1)短信发送
	 *   *号头前标注的地址表示失败后不能再使用,其它情况若失败按顺序选取
	 *   若多个号码表示时用[]包围发送内容
	 * 	<Address>13532565214</Address> 一个主号发送
	 * 	<Address>[13532565214＆*15245241248＆13565245298]</Address> 主从号码短信若失败按配置顺序发送
	 *  <Address>{MCCMNC}[13532565214|15245241248|13565245298]</Address> 从几个|号分隔的内容中随机选取发送地址
	 *  
	 * 2)Http协议发送
	 * <Address>www.test.com</Address> 一个主号发送
	 */
	
	private class AddressParser{
		private String address;
		private int index = 0;
		private List<Address> AddressList = null;
		
		public AddressParser(String address){
			this.address = address;
			AddressList = new ArrayList<Address>();
		}
		
	    private void parserAddress() throws Exception{
		   	int AddressNum = 0;
		   	int lastStatus = 0;

		   	if(address == null){
		   		return;
		   	}

			AddressNum = getAddressNumber(address);
			if(AddressNum == 1){
				AddressList.add(new Address(0, address));
				return;
			}
			else if(AddressNum > 1){

				//字符串扫描  状态对应值
				//0:初始状态；  1：短信字符串读取(顺序)； 2：短信字符串读取(随机)； 3：Http地址字符串开始读取
				int status = 0;
				char[] expChars = address.trim().toCharArray();
			
				StringBuffer tokenBuffer = new StringBuffer();
				for(int i = 0 ; i < expChars.length ; i++){
		
					if(' ' == expChars[i]){
						continue;
					}

					if('[' == expChars[i]){ //多个地址读取开始
		
					}
					else if(']' == expChars[i]){ //多个地址读取结束
					
						if(status == 0){
							throw new Exception("非法的首位置出现:[" + expChars[i] + "],位置：" + i);
						}
						else if(status == 1){
							status = 0;
							AddressList.add(new Address(index++, tokenBuffer.toString()));
						}
						else if(status == 2){
							AddressList.add(new Address(index, tokenBuffer.toString()));
						}
						else if(status == 3){
							if(lastStatus == 1){
								AddressList.add(new Address(index++, tokenBuffer.toString()));
							}
							else if(lastStatus == 2){
								AddressList.add(new Address(index, tokenBuffer.toString()));
							}
						}
					}
					else if('&' == expChars[i]){ //多个顺序地址读取结束
						if(status == 0 || (preReadNext(expChars[i+1]) == -1)){
							throw new Exception("非法字符出现:[" + expChars[i] + "],位置：" + i);
						}
						else if(status == 1 || status == 2){
							AddressList.add(new Address(index++, tokenBuffer.toString()));
						}else if(status == 3){
							if(lastStatus == 1){
								AddressList.add(new Address(index++, tokenBuffer.toString()));
							}
							else if(lastStatus == 2){
								AddressList.add(new Address(index, tokenBuffer.toString()));
							}
							status = lastStatus;
						}
						
						tokenBuffer= new StringBuffer(); //清空buffer
					}
					else if('|' == expChars[i]){ //多个随机地址读取结束
						if(status == 0 || (preReadNext(expChars[i+1]) == -1)){
							throw new Exception("首位置不允许出现:[" + expChars[i] + "]，位置：" + i);
						}
						else if(status == 1 || status == 2){
							status = 2;
							AddressList.add(new Address(index, tokenBuffer.toString()));
						}
						else if(status == 3){
							if(lastStatus == 1){
								AddressList.add(new Address(index++, tokenBuffer.toString()));
							}
							else if(lastStatus == 2){
								AddressList.add(new Address(index, tokenBuffer.toString()));
							}
							status = lastStatus;
						}
						
						tokenBuffer= new StringBuffer(); //清空buffer
					}
					else if('*' == expChars[i]){ //标记地址不可复用或网址分隔符
					
						if(preReadNext(expChars[i+1]) == -1){
							throw new Exception("* 后非法字符:[" + expChars[i] + "],位置：" + i);
						}
						
						if(status == 0){//短信号码标记
		
							//通过下一个字符进行判断
							if(isNumber(expChars[i+1])){
								status = 0;
								tokenBuffer.append(expChars[i]);
							}
							else if(isUrlCharacter(expChars[i+1])){
								status = 3; //http
								tokenBuffer.append(expChars[i]);
							}
						}
						else if(status == 1 || status == 2 || status == 3){
							tokenBuffer.append(expChars[i]);
						}
					}
					else if(isNumber(expChars[i])){ //短信号码
						if(status == 0){
							status = 1;
							tokenBuffer.append(expChars[i]);
						}
						else if(status == 1 || status == 2 || status == 3){
							tokenBuffer.append(expChars[i]);
						}
					}
					else if(isUrlCharacter(expChars[i])){ //http地址
						if(status == 0){
							status = 3;
							tokenBuffer.append(expChars[i]);
						}
						else if(status == 1 || status == 2 || status == 3){
							if(status != 3){
								lastStatus = status;
								
								status = 3;
							}
							tokenBuffer.append(expChars[i]);
						}
					}
					else{
						if(!isUrlCharacter(expChars[i])){
							throw new Exception("未知的字符:[" + expChars[i] + "],位置：" + i);
						}
					}
		
					//结束时
					if(i == expChars.length - 1){
						if(status == 1 || lastStatus == 1){
							AddressList.add(new Address(index++, tokenBuffer.toString()));
						}
						else if(status == 2 || lastStatus == 2){
							AddressList.add(new Address(index, tokenBuffer.toString()));
						}
					}
				}//结束字符串扫描
			}
	   	}
	    
	    public List<Address> getAddressList(){
	    	return AddressList;
	    }

		private int preReadNext(char c){
			if('*' == c || ' ' == c || isNumber(c) || isCharacter(c)){
				return 0;
			}
			else{
				return -1;
			}
		}

		private int getAddressNumber(String address){
			int num = 1;
			for(int i = 0 ; i < address.length() ; i++){
				if(address.charAt(i) == '&' || address.charAt(i) == '|'){
					num++; 
				}
			}
			return num;
		}

		private boolean isNumber(char c){
			if((c >= '0' && c <= '9')){
				return true;
			}else{
				return false;
			}
		}

		private boolean isCharacter(char c){
			if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
				return true;
			}else{
				return false;
			}
		}

		private boolean isUrlCharacter(char c){
		
			final String URL_SPECIAL_CHARACTER = ":/+?&%#.-_="; //URL特殊字符

		    if(isCharacter(c) || URL_SPECIAL_CHARACTER.indexOf(c) > -1){
		        	return true;
		    }
		    
			return false;
		}
	}

	//获取最终发送字符串
	public String getSendMessage(){
		
		mMessage = Util.getStringPref(mContext, SalesTrackerService.KEY_LAST_MESSAGE, "");
		if(mMessage != null && !mMessage.equals("")){
			return mMessage;
		}
		
		List<String> ItemListResult = new ArrayList<String>();
		MessageItem items =  new MessageItem(mContext);
		for(int i = 0; i < mItemList.size(); i++){
			ItemListResult.add(items.getItemValues(mItemList.get(i)));
		}
		
		if(Featrue.isDebug){
			for(int i = 0; i < mItemList.size(); i++){
				Log.i(TAG, mItemList.get(i) + "==>[" + ItemListResult.get(i) + "]");
			}
		}

		if(mMessageConfig == null || ItemListResult.isEmpty()){
			Log.e(TAG, "get Send Message error!");
			return null;
		}
		
		String MessageContent = String.format(mMessageConfig, ItemListResult.toArray());

		Log.d(TAG, "Get Send Message is:[" + MessageContent + "]");
		Util.setStringPref(mContext, SalesTrackerService.KEY_LAST_MESSAGE, MessageContent);

		return MessageContent;
	}
	
	//获取发送地址对象
	public Address getSendAddress(){

		if(mAddressList == null || mAddressList.isEmpty()){
			Log.e(TAG,"getSendAddress is null");
			
			return null;
		}
		
		int num = mAddressList.size();
		Address address =  null;
		
		//从未发送过
		if(!mSendFail){
		    mSendFail = true;
		    address =  mAddressList.get(0);
		    address.setRetry(true);
		}
		else{
		      //只有一个地址时用第一个发送
	        if(num == 1){
	            address =  mAddressList.get(0);
	        }
	        else{
	            boolean isChoose = false;
	            List<Address> randomAddress = null;
	            int chooseNum = mAddressList.get(num - 1).getAddressIndex() - mAddressList.get(0).getAddressIndex() + 1;
	            mLastAddressIndex++;
	            
	            //选用原则：从 index 从小到大遍历:标明只用一次的跳过;已用的跳过;相同的在其中随机选择一个
	            
	            int index = 0;
	            while(!isChoose){
	                
	                for(int i = 0; i < num; i++){
	                    address =  mAddressList.get(i);
	                    index = address.getAddressIndex();
	                    
	                    if(index == mLastAddressIndex % chooseNum){
	                        
	                        if(randomAddress == null){
                                randomAddress = new ArrayList<Address>();
                            }
                            
                            randomAddress.add(address);
	                    }
	                } 
	                
	                //secelt address from address random list
	                if(randomAddress.size() == 1){
	                    address = randomAddress.get(0);
	                    isChoose = true;
	                }
	                else{
	                    Address addr = chooseAddress(randomAddress);
	                    randomAddress.clear();
	                    
	                    if(addr == null){
	                        continue;
	                    }
	                    else{
	                        address = addr;
	                        addr.setRetry(true);
                            isChoose = true;
	                    }
	                }
	                
	                //遍历未找到，取第一个重复使用的那个，其他切换状态
	                if(!isChoose){
	                    
	                    for(int i = 0; i < num; i++){
	                        Address addr =  mAddressList.get(i);
	                        if(addr.isRetry() && !addr.isRepeatUse()){
	                            addr.setRetry(false);
	                        }
	                    }
	                }
	            }
	        }
		}

		return address;
	}
	
	
	private Address chooseAddress(List<Address> addresses){
	    Address address = null;
		int len = addresses.size();
		int index = 0;

		for(int i = 0; i < len * 3; i++){
			index = (int)(Math.random() * len);
			Address addr = addresses.get(index);
			if(addr.isRetry() && !addr.isRepeatUse()){
				address =  addr;
				addr.setRetry(true);  //mark address is used
				break;
			}
		}

		return address;
	}

}
